package com.rongke.web.api;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.commons.PageDto;
import com.rongke.mapper.AdminMapper;
import com.rongke.model.*;
import com.rongke.service.*;

import com.rongke.utils.Md5;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.util.*;

/**
 * @AdminController
 * @管理员Controller
 * @version : Ver 1.0
 */
@RestController
@RequestMapping(value="/api/admin")
@Transactional
@CrossOrigin
public class AdminController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleThirdCatalogueService roleThirdCatalogueService;
    @Autowired
    private ThirdCatalogueService thirdCatalogueService;
    @Autowired
    private ChannelService channelService;
    /**
     * @添加管理员
     * @param admin
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/add", method = RequestMethod.POST)
    public JsonResp addAdmin(@RequestBody Admin admin){
        log.debug("添加管理员");
        if (admin.getPhone().equals("")){
            return   JsonResp.fa("电话未填写");
        }else if (admin.getPassword().equals("")){
            return   JsonResp.fa("密码未填写");
        }else if (admin.getUserName().equals("")){
            return   JsonResp.fa("用户名未填写");
        }else if (admin.getRoleId()==null){
            return   JsonResp.fa("未选择角色");
        }

        EntityWrapper entity=new EntityWrapper();
        entity.eq("user_name",admin.getUserName());
        List<Admin> adminList=adminService.selectList(entity);
        if (!adminList.isEmpty()){
            return JsonResp.fa("不能添加相同的账户名称");
        }
        EntityWrapper entity1=new EntityWrapper();
        entity1.eq("login_name",admin.getUserName());
        List<Channel> channelList=channelService.selectList(entity);
        if (!adminList.isEmpty()){
            return JsonResp.fa("不能添加和代理商相同的账户名称");
        }
        admin.setGmtDatetime(new Date());
        admin.setUptDatetime(new Date());
        admin.setPassword(Md5.md5Encode(admin.getPassword()));
        adminService.insert(admin);
        return JsonResp.ok(admin);
    }

    /**
     * @修改管理员
     * @param admin
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/update", method = RequestMethod.POST)
    public JsonResp updateAdmin(@RequestBody Admin admin){
        log.debug("修改管理员");
        if (admin.getPhone().equals("")){
            return   JsonResp.fa("电话未填写");
        }else if (admin.getUserName().equals("")){
            return   JsonResp.fa("用户名未填写");
        }else if (admin.getRoleId().equals("")){
            return   JsonResp.fa("未选择角色");
        }
        String [] str=admin.getPassword().split("=@@=");
         Integer sun=0;
         for (String sr:str){
             sun++;
              if (sun==1){
                  admin.setPassword(sr);
              }else if (sun==2){
              if (!sr.equals("")){
                 admin.setPassword(Md5.md5Encode(sr));
              }
              }
         }
           EntityWrapper entity=new EntityWrapper();
           entity.eq("user_name",admin.getUserName());
           List<Admin> adminList=adminService.selectList(entity);
              if (!adminList.isEmpty()){
                  return JsonResp.fa("不能修改相同的账户名称");
              }
        EntityWrapper entity1=new EntityWrapper();
        entity1.eq("login_name",admin.getUserName());
        List<Channel> channelList=channelService.selectList(entity);
        if (!adminList.isEmpty()){
            return JsonResp.fa("不能修改和代理商相同的账户名称");
        }
        adminService.updateById(admin);
        return JsonResp.ok(admin);
    }
    /**
     * @根据id查找管理员
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/selectOne", method = RequestMethod.GET)
    public JsonResp selectAdmin(Long id){
        log.debug("查找管理员");
        Admin admin = adminService.selectById(id);
        return JsonResp.ok(admin);
    }



    /***
     * 后台管理员账户
     * */
     @RequestMapping(value = "/selectAdministrator",method = RequestMethod.GET)
     public  JsonResp selectAdministrator(Page page,Admin admin){
         Map map=new HashMap();
         map.put("pageNo",(page.getCurrent()-1)*page.getSize());
         map.put("pageSize",page.getSize());
         map.put("admin",admin);
         List<Admin>  adminList=adminService.selectAdmin(map);
         Integer  sun=adminService.selectAdminCount(map);

         return JsonResp.ok(new PageDto(page.getCurrent(),page.getSize(),adminList,sun));
     }



     /***
      * 角色管理
      * */
   @RequestMapping(value = "/selectroleAll",method = RequestMethod.GET)
    public JsonResp selectroleAll(Page page){
       Page<Role> rogePage = roleService.selectPage(page,null);
       return JsonResp.dataPage(rogePage);
   }

    @RequestMapping(value = "/agselectroleAll",method = RequestMethod.GET)
    public JsonResp agselectroleAll(){
        List<Role> roleList= roleService.selectList(null);
        return JsonResp.ok(roleList);
    }

     /**
      * 管理员删除
      * */
   @RequestMapping(value = "/admindelect",method = RequestMethod.POST)
    public JsonResp karakters(@RequestBody Admin admin){
       Boolean bo=false;
           if (admin.getStatus()==3){
               bo= adminService.deleteById(admin.getId());
               return JsonResp.ok(bo);
           }
           bo= adminService.updateById(admin);
       return JsonResp.ok(bo);
   }



    /**
     * 角色删除 修改
     * */
    @RequestMapping(value = "/jaosedelect",method = RequestMethod.GET)
    public JsonResp karakters(Role role){
        Boolean bo=false;
        if (role.getStatus()==2){
             EntityWrapper  entityWrappe=new EntityWrapper();
               entityWrappe.eq("role_id",role.getId());
               List<Admin> adminList=adminService.selectList(entityWrappe);
               List<RoleThirdCatalogue> roleThirdCatalogueList= roleThirdCatalogueService.selectList(entityWrappe);
                     if (!adminList.isEmpty()){
                     return JsonResp.fa("该角色不能删除在管理员有引用");
                     }else if(!roleThirdCatalogueList.isEmpty()){
                     return JsonResp.fa("该角色在功能权限上有引用");
                     }else{
                    bo= roleService.deleteById(role.getId());
                        // return JsonResp.ok(bo);
                     }
        }else if(role.getStatus()==1){
            bo= roleService.updateById(role);

        }
        return JsonResp.ok(bo);
    }


/***
 *
 * 查询所有角色
 * */

    @RequestMapping(value = "/selectRole",method = RequestMethod.GET)
    public JsonResp selectRole(){


        return JsonResp.ok();
    }



    /*******
     *
     *
     * 权限查询
     *
     * */


    @RequestMapping(value="/findAll", method = RequestMethod.GET)
    public JsonResp findAll(Long roleId){
        log.debug("查询三级目录");
        List<ThirdCatalogue> list = thirdCatalogueService.findAll();
        List<ThirdCatalogue> list1 = thirdCatalogueService.findAllSecond();
        EntityWrapper<RoleThirdCatalogue> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("role_id",roleId);
        List<RoleThirdCatalogue> list2 = roleThirdCatalogueService.selectList(entityWrapper);
        StringBuffer thirdMenu = new StringBuffer("[");
        for (int j = 0; j < list1.size(); j++) {
            if (j != 0) {
                thirdMenu.append(",");
            }
            thirdMenu.append("{\"first\":{\"title\":\""+list1.get(j).getSecond().getFirst().getTitle()+"\",\"second\":{\"title\":\""+list1.get(j).getSecond().getTitle()+"\",\"third\":[");
            int num = 0;
            for (int i = 0; i < list.size(); i++) {
                if (list1.get(j).getSecond().getTitle().equals(list.get(i).getSecond().getTitle())) {
                    if (num != 0) {
                        thirdMenu.append(",");
                    }
                    String text="{\"title\":\"" + list.get(i).getTitle() + "\",\"data\":" + list.get(i).getId() + ",\"select\":0}";
                    for (RoleThirdCatalogue role : list2) {
                        if (role.getThirdCatalogueId() == list.get(i).getId()) {
                            text = "{\"title\":\"" + list.get(i).getTitle() + "\",\"data\":" + list.get(i).getId() + ",\"select\":1}";
                            break;
                        }
                    }
                    thirdMenu.append(text);
                    num = 1;
                }
            }
            thirdMenu.append("]}}}");
        }
        thirdMenu.append("]");
        String jsonString = thirdMenu.toString();
        JSONArray json = JSONArray.parseArray(jsonString);
        return JsonResp.ok(json);
    }

    /**
     * @添加角色功能
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/addList", method = RequestMethod.POST)
    public JsonResp addList(String title,Long roleId,@RequestBody List<Long> ids){
        log.debug("添加角色功能");
        Role role = new Role();
        List<RoleThirdCatalogue> list = new ArrayList<>();
        if (null != roleId && !roleId.equals("")) {
            role.setId(roleId);
            EntityWrapper<RoleThirdCatalogue> wrapper = new EntityWrapper<>();
            wrapper.eq("role_id",roleId);
            roleThirdCatalogueService.delete(wrapper);
        }
        role.setTitle(title);
        roleService.insertOrUpdate(role);
        for (Long id : ids) {
            RoleThirdCatalogue catalogue = new RoleThirdCatalogue();
            catalogue.setRoleId(role.getId());
            catalogue.setThirdCatalogueId(id);
            list.add(catalogue);
        }
        roleThirdCatalogueService.insertBatch(list);
        return JsonResp.ok();
    }
    /**
     * @分页查询角色-功能关联
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value="/findByPage", method = RequestMethod.POST)
    public JsonResp findByPage(Integer pageNo,Integer pageSize,Long roleId,@RequestBody ThirdCatalogue catalogue){
        log.debug("分页查询角色-功能关联");
        Map<String,Object> map = new HashMap<>();
        map.put("roleId",roleId);
        map.put("pageNo",(pageNo-1)*pageSize);
        map.put("pageSize",pageSize);
        map.put("firstTitle",catalogue.getSecond().getFirst().getTitle());
        map.put("secondTitle",catalogue.getSecond().getTitle());
        map.put("thirdTitle",catalogue.getTitle());
        Integer total = roleThirdCatalogueService.findByPageCount(map);
        List<RoleThirdCatalogue> list = roleThirdCatalogueService.findByPage(map);
        return JsonResp.ok(new PageDto(pageNo,pageSize,list,total));
    }




    /***删除角色功能关联*/
    @RequestMapping(value="/deleteOne", method = RequestMethod.GET)
    public JsonResp deleteRoleThirdCatalogue(Long id){
        log.debug("删除角色-功能关联");
        roleThirdCatalogueService.deleteById(id);
        return JsonResp.ok();
    }

    /**
     * 登录
     *
     * @param userName 用户名
     * @param password 密码
     * @return JsonResp
     * @throws UnsupportedEncodingException
     */
    @RequestMapping(value = "/loginPhoneadmin", method = RequestMethod.GET)
    public JsonResp login(String userName, String password) throws UnsupportedEncodingException {
        log.debug("登录");
        return adminService.loginadmin(URLDecoder.decode(userName, "utf-8"), password);
    }



    /**
     * 注销
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public JsonResp logout() {
        log.debug("注销");
        adminService.logout();
        return JsonResp.ok();
    }
    /**
     * 获取当前用户信息
     * @return
     */
    @RequestMapping(value="/getAdminInfo", method = RequestMethod.GET)
    public JsonResp getUserInfo(){
        log.debug("获取当前用户信息");
        Map user=adminService.findLoginUser();
        return JsonResp.ok(user);
    }




}
